import { NextResponse } from 'next/server';
import { verifyToken } from '@/utils/auth';
import UserModel from '@/models/user';

// GET 请求处理器 - 获取用户的招聘公告列表
export async function GET(request: Request) {
  try {
    // 验证用户身份
    const authHeader = request.headers.get('authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const token = authHeader.split(' ')[1];
    const payload = verifyToken(token);

    if (!payload || !payload.id) {
      return NextResponse.json({ error: '无效的令牌' }, { status: 401 });
    }

    const userId = payload.id;

    // 从数据库获取用户发布的招聘公告
    const [jobPosts] = await UserModel.query<any[]>(
      `SELECT jp.id, jp.company_id, jp.title, jp.description, jp.requirements, 
              jp.salary_range, jp.location, jp.job_type, jp.experience, jp.education, 
              jp.status, jp.application_count, jp.created_by,
              DATE_FORMAT(jp.created_at, '%Y-%m-%d %H:%i:%s') as created_at,
              DATE_FORMAT(jp.updated_at, '%Y-%m-%d %H:%i:%s') as updated_at,
              c.name as company_name, c.logo as company_logo, c.industry as company_industry,
              c.size as company_size
       FROM job_positions jp
       LEFT JOIN companies c ON jp.company_id = c.id
       WHERE jp.created_by = ?
       ORDER BY jp.created_at DESC`,
      [userId]
    );

    // 转换数据格式以匹配前端期望的格式
    const formattedJobPosts = jobPosts.map(post => ({
      id: post.id,
      title: post.title,
      company_name: post.company_name || '未知公司',
      location: post.location,
      salary_min: null, // job_positions表使用salary_range字段
      salary_max: null,
      salary_range: post.salary_range, // 添加这个字段
      job_type: post.job_type,
      is_active: post.status === 'active',
      views: 0, // job_positions表没有views字段，暂时设为0
      applications: post.application_count || 0,
      created_at: post.created_at,
      description: post.description,
      requirements: post.requirements
    }));

    console.log(`获取招聘公告列表: 用户ID=${userId}, 公告数量=${formattedJobPosts.length}`);

    return NextResponse.json(formattedJobPosts);
  } catch (error) {
    console.error('获取招聘公告列表失败:', error);
    return NextResponse.json(
      { error: `获取招聘公告列表失败: ${(error as Error).message}` },
      { status: 500 }
    );
  }
} 